﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.AspNetCore.SignalR.Client;
using YXChatFormClient.Dtos.Account;
using YXChatFormClient.Dtos.ChatRecord;

namespace YXChatFormClient.Utility.HubHelp
{
    public class ChatService
    {
        public static HubConnection Connection;

        /// <summary>
        /// 初始化连接
        /// </summary>
        public static async void InitSignalRConnection()
        {
            Connection = new HubConnectionBuilder()
                .WithUrl($"{Api.ServerUrl}yxChat/chatHub")
                .Build();
            await Connection.StartAsync();
            Connection.Closed += async error =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);
                await Connection.StartAsync();
            };
        }

        /// <summary>
        /// 监听添加好友
        /// </summary>
        public static void ReceiveAddBuddyNotify(Action<AccountDto> action)
        {
            Connection.On<AccountDto>("AddBuddyNotify", buddyAccount =>
            {
                Task.Run(() =>
                {
                    action(buddyAccount);
                });
            });
        }
        /// <summary>
        /// 让服务端添加客户端连接id
        /// </summary>
        /// <param name="accountNumber"></param>
        public static void NotifyServiceAddClient(string accountNumber)
        {
            Connection.InvokeAsync<string>("AddClient", accountNumber);
        }
        public static void ReceiveSendMessage(Action<MessageNotifyDto> action)
        {
            Connection.On("SendMessage", action);
        }

    }
}
